package com.mobilottery.ui;

import com.mobilottery.server.PersistenceManager;
import com.mobilottery.server.User;
import com.mobilottery.server.UserManager;

/**
 * Baking bean for updating profile form
 * @author fedor
 */
public class UpdateProfileForm extends RegisterForm 
{
	String newPassword;
	
	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	@Override
	protected boolean validateUser()
	{
		if(!UserManager.getInstance().isLoginMatch(userName, password))
		{
			setFieldErorrMessage("userName", "User password does not match");
			return false;
		}
		return true;
	}
	
	
	@Override
	protected void validate()
	{
		validateUser();
		validateMail("email", email);
		validateName("firstName", firstName);
		validateCreditCard("creditCardNumber", creditCardNumber);	
		if(newPassword!=null && !newPassword.isEmpty())
			validatePassword("newPassword", newPassword);
		validateName("lastName", lastName);
	}
	
	
	public void reset(User u)
	{
		super.reset();
	    userName = u.getUserName();
	    email = u.getEmail();
	    firstName = u.getFirstName();
	    lastName = u.getLastName();
	    newPassword = "";
	    creditCardNumber = u.getCreditCardNumber();		
	}	

	@Override
	protected void performSubmit()
	{
		User user = UserManager.getInstance().getUser(userName);
		user.setEmail(email);
		user.setFirstName(firstName);
		user.setLastName(lastName);
		//ingore empty new password
		if(newPassword.length()>0)
			user.setPasswordText(newPassword);
		user.setCreditCardNumber(creditCardNumber);
		PersistenceManager.getInstance().persist(user);
	}
	
}
